package com.scs.application.modules.upms.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.upms.entity.GenDatasource;
import com.scs.application.modules.upms.mapper.GenDataSourceMapper;
import com.scs.application.modules.upms.service.GenDatasourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:DictTypeServiceImpl
 **/
@Slf4j
@Service
public class GenDatasourceServiceImpl extends BaseServiceImpl<GenDataSourceMapper, GenDatasource> implements GenDatasourceService, DisposableBean {

    private final ConcurrentHashMap<String, DruidDataSource> datasourceMap = new ConcurrentHashMap<>();


    @Override
    public DataSource getRealDatasource(String id) {
        DruidDataSource source = datasourceMap.get(id);
        if (source != null) {
            return source;
        }
        GenDatasource genDatasource = this.getById(id);
        if (genDatasource == null) {
            return null;
        }

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setName(genDatasource.getName());
        dataSource.setUrl(genDatasource.getUrl());
        dataSource.setUsername(genDatasource.getUsername());
        dataSource.setPassword(genDatasource.getPassword());
        dataSource.setInitialSize(0);
        dataSource.setMaxActive(10);

        datasourceMap.put(id, dataSource);

        return dataSource;
    }

    @Override
    public void clearCache() {
        try {
            destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        datasourceMap.clear();
    }


    @Override
    public void destroy() throws Exception {
        if (datasourceMap.isEmpty()) {
            return;
        }

        log.info("closing all gen datasource");
        datasourceMap.forEachValue(1, o -> o.close());
        log.info("closed all gen datasource,datasource count is {}", datasourceMap.size());

    }
}
